<template>
  <div class="common-container">
    <div class="common-header">
      <h2>字典管理</h2>
    </div>
    
    <!-- 查询条件和操作按钮 -->
    <div class="common-search-bar">
      <el-form :inline="true" :model="queryForm" class="common-search-form">
        <el-form-item label="字典类型">
          <el-input 
            v-model="queryForm.dictType" 
            placeholder="请输入字典类型" 
            clearable
            style="width: 180px;"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="字典名称">
          <el-input 
            v-model="queryForm.dictName" 
            placeholder="请输入字典名称" 
            clearable
            style="width: 180px;"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="dictionariesLoading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-left: auto;">
          <input
            ref="importInput"
            type="file"
            accept=".xlsx,.xls"
            style="display: none;"
            @change="handleFileImport"
          />
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增字典
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出字典
          </el-button>
          <el-button @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入字典
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="common-table-card">
      <el-table 
        :data="dictionaries" 
        style="width: 100%;" 
        v-loading="dictionariesLoading"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="dictType" label="字典类型" min-width="120" />
        <el-table-column prop="dictName" label="字典名称" min-width="120" />
        <el-table-column prop="dictCode" label="字典编码" min-width="120" />
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="common-pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>
    
    <!-- 字典编辑/新增对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="dictFormRef" 
        :model="dictForm" 
        :rules="dictFormRules" 
        label-width="80px"
      >
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="dictForm.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="dictForm.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="dictCode">
          <el-input v-model="dictForm.dictCode" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number 
            v-model="dictForm.sortOrder" 
            :min="0" 
            :max="9999"
            placeholder="请输入排序"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dictForm.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="common-dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Download, Upload } from '@element-plus/icons-vue'
import { getDictionaryList, createDictionary, updateDictionary, deleteDictionary, exportDictionary, importDictionary } from '../utils/api'

export default {
  name: 'DictionaryManagement',
  components: {
    Plus,
    Search,
    Download,
    Upload
  },
  setup() {
    const dictionaries = ref([])
    const dictionariesLoading = ref(false)
    const dialogVisible = ref(false)
    const submitLoading = ref(false)
    const isEdit = ref(false)
    const dictFormRef = ref()
    
    // 查询表单
    const queryForm = ref({
      dictType: '',
      dictName: ''
    })
    
    // 分页数据
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 计算表格高度
    const tableHeight = computed(() => {
      return 'calc(100vh - 284px)'
    })
    
    const dictForm = ref({
      id: null,
      dictType: '',
      dictName: '',
      dictCode: '',
      sortOrder: 0,
      status: 1
    })
    
    const dictFormRules = {
      dictType: [
        { required: true, message: '请输入字典类型', trigger: 'blur' },
        { min: 1, max: 50, message: '字典类型长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      dictName: [
        { required: true, message: '请输入字典名称', trigger: 'blur' },
        { min: 1, max: 100, message: '字典名称长度在 1 到 100 个字符', trigger: 'blur' }
      ],
      dictCode: [
        { required: true, message: '请输入字典编码', trigger: 'blur' },
        { min: 1, max: 50, message: '字典编码长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      sortOrder: [
        { required: true, message: '请输入排序', trigger: 'blur' },
        { type: 'number', min: 0, max: 9999, message: '排序必须在 0 到 9999 之间', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑字典' : '新增字典'
    })
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString('zh-CN')
    }
    
    // 加载字典列表
    const loadDictionaries = async () => {
      dictionariesLoading.value = true
      try {
        const params = {
          page: pagination.value.page,
          size: pagination.value.size
        }
        if (queryForm.value.dictType) {
          params.dictType = queryForm.value.dictType
        }
        if (queryForm.value.dictName) {
          params.dictName = queryForm.value.dictName
        }
        
        const response = await getDictionaryList(params)
        if (response.data.code === 200) {
          const data = response.data.data
          dictionaries.value = data.records || data
          pagination.value.total = data.total || dictionaries.value.length
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('获取字典列表失败')
      } finally {
        dictionariesLoading.value = false
      }
    }
    
    // 查询功能
    const handleSearch = () => {
      pagination.value.page = 1
      loadDictionaries()
    }
    
    // 重置查询
    const handleReset = () => {
      queryForm.value.dictType = ''
      queryForm.value.dictName = ''
      pagination.value.page = 1
      loadDictionaries()
    }
    
    // 分页大小改变
    const handleSizeChange = (newSize) => {
      pagination.value.size = newSize
      pagination.value.page = 1
      loadDictionaries()
    }
    
    // 当前页改变
    const handleCurrentChange = (newPage) => {
      pagination.value.page = newPage
      loadDictionaries()
    }
    
    // 新增字典
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑字典
    const handleEdit = (row) => {
      isEdit.value = true
      dictForm.value = {
        id: row.id,
        dictType: row.dictType,
        dictName: row.dictName,
        dictCode: row.dictCode,
        sortOrder: row.sortOrder,
        status: row.status
      }
      dialogVisible.value = true
    }
    
    // 删除字典
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定要删除字典 ${row.dictName} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteDictionary(row.id)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          loadDictionaries() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!dictFormRef.value) return
      
      try {
        await dictFormRef.value.validate()
        submitLoading.value = true
        
        let response
        if (isEdit.value) {
          // 编辑字典
          response = await updateDictionary(dictForm.value.id, dictForm.value)
        } else {
          // 新增字典
          response = await createDictionary(dictForm.value)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          loadDictionaries() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      dictForm.value = {
        id: null,
        dictType: '',
        dictName: '',
        dictCode: '',
        sortOrder: 0,
        status: 1
      }
      if (dictFormRef.value) {
        dictFormRef.value.resetFields()
      }
    }

    // 导出字典
    const handleExport = async () => {
      try {
        const response = await exportDictionary()
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `字典数据_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败')
      }
    }

    // 导入字典
    const handleImport = () => {
      const importInput = document.querySelector('input[type="file"]')
      if (importInput) {
        importInput.click()
      }
    }

    // 处理文件导入
    const handleFileImport = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      const validExtensions = ['.xlsx', '.xls']
      const fileExtension = file.name.substring(file.name.lastIndexOf('.'))
      if (!validExtensions.includes(fileExtension.toLowerCase())) {
        ElMessage.error('请上传Excel文件（.xlsx或.xls格式）')
        // 清空input的值，否则相同文件无法触发change事件
        event.target.value = ''
        return
      }

      try {
        await ElMessageBox.confirm('确定要导入字典数据吗？导入将覆盖现有数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await importDictionary(file)
        if (response.data.code === 200) {
          ElMessage.success('导入成功')
          loadDictionaries() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('导入失败')
        }
      } finally {
        // 清空input的值
        event.target.value = ''
      }
    }
    
    onMounted(() => {
      loadDictionaries()
    })
    
    return {
      dictionaries,
      dictionariesLoading,
      dialogVisible,
      submitLoading,
      dictForm,
      dictFormRules,
      dictFormRef,
      queryForm,
      pagination,
      tableHeight,
      dialogTitle,
      formatDateTime,
      loadDictionaries,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      resetForm,
      handleExport,
      handleImport,
      handleFileImport
    }
  }
}
</script>

<style scoped>

</style>